package model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Storage {
	
	private ObjectMapper mapper;
	private XStream xstream;
	
	public Storage(){
		mapper = new ObjectMapper();
		xstream = new XStream(new DomDriver());
	}
	
	/***
	 * Save a json file
	 * @param list
	 * @param path
	 */
	public void jsonSerialization(MoviesList list, String path){
		try {
			mapper.writeValue(new File(path),list);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	/**
	 * Load a json file
	 * @param path 
	 * @return the movies list
	 */
	public MoviesList jsonDeserialization(String path){
		MoviesList list = null;
		try {
			list = mapper.readValue(new File(path), MoviesList.class);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	/***
	 * Save a xml file
	 * @param list
	 * @param path
	 */
	public void xmlSerialization(MoviesList list, String path){
        try {
            xstream.toXML(list,new FileOutputStream(path));	
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        }
	}
	
	/***
	 * load a xml file
	 * @param path 
	 * @return the movies list
	 */
	public MoviesList xmlDeserialization(String path){
		MoviesList list = null;
		try {
			list = (MoviesList) xstream.fromXML(new FileInputStream(new File(path)));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;      
	}

}
